Lambda表达式的几种使用方式 您所在的位置:网站首页 java methodinvoke Lambda表达式的几种使用方式

Lambda表达式的几种使用方式

#Lambda表达式的几种使用方式| 来源: 网络整理| 查看: 265

Lambda 的表达式的编写格式如下:

x=> x * 1.5

当中 “ => ” 是 Lambda 表达式的操作符,在左边用作定义一个参数列表,右边可以操作这些参数。

例一, 先把 int x 设置 1000,通过 Action 把表达式定义为 x=x+500 ,最后通过 Invoke 激发委托。

1 static void Main(string[] args) 2 { 3 int x = 1000; 4 Action action = () => x = x + 500; 5 action.Invoke(); 6 7 Console.WriteLine("Result is : " + x); 8 Console.ReadKey(); 9 }

例二,通过 Action 把表达式定义 x=x+500, 到最后输入参数1000,得到的结果与例子一相同。注意,此处Lambda表达式定义的操作使用 { } 括弧包括在一起,里面可以包含一系列的操作。

  1 static void Main(string[] args)2 {3 Action action = (x) =>4 {5 x = x + 500;6 Console.WriteLine("Result is : " + x);7 };8 action.Invoke(1000);9 Console.ReadKey(); 10 }

 

例三,定义一个Predicate,当输入值大约等于1000则返回 true , 否则返回 false。与5.3.1的例子相比,Predicate的绑定不需要显式建立一个方法,而是直接在Lambda表达式里完成,简洁方 便了不少。

  1 static void Main(string[] args)2 {3 Predicate predicate = (x) =>4 {5 if (x >= 1000)6 return true;7 else8 return false;9 }; 10 bool result=predicate.Invoke(500); 11 Console.ReadKey(); 12 }

 

例四,在计算商品的价格时,当商品重量超过30kg则打9折,其他按原价处理。此时可以使用Func,参数1为商品原价,参数2为商品重量,最后返回值为 double 类型。

  1 static void Main(string[] args)2 {3 Func func = (price, weight) =>4 {5 if (weight >= 30)6 return price * 0.9;7 else8 return price;9 }; 10 double totalPrice = func(200.0, 40); 11 Console.ReadKey(); 12 }

例五,使用Lambda为Button定义Click事件的处理方法。与5.2的例子相比,使用Lambda比使用匿名方法更加简单。

1 static void Main(string[] args) 2 { 3 Button btn = new Button(); 4 btn.Click += (obj, e) => 5 { 6 MessageBox.Show("Hello World!"); 7 }; 8 Console.ReadKey(); 9 }

例六,此处使用5.3.1的例子,在List的FindAll方法中直接使用Lambda表达式。相比之下,使用Lambda表达式,不需要定义Predicate对象,也不需要显式设定绑定方法,简化了不工序。

1 class Program2 {3 static void Main(string[] args)4 {5 List personList = GetList();6 7 //查找年龄少于30年的人8 List result=personList.FindAll((person) => person.Age =< 30);9 Console.WriteLine("Person count is : " + result.Count); 10 Console.ReadKey(); 11 } 12 13 //模拟源数据 14 static List GetList() 15 { 16 var personList = new List(); 17 var person1 = new Person(1,"Leslie",29); 18 personList.Add(person1); 19 ....... 20 return personList; 21 } 22 } 23 24 public class Person 25 { 26 public Person(int id, string name, int age) 27 { 28 ID = id; 29 Name = name; 30 Age = age; 31 } 32 33 public int ID 34 { get; set; } 35 public string Name 36 { get; set; } 37 public int Age 38 { get; set; } 39 }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有